<?php

function init_db_info($db_table_prefix){

  //初始化数据库
  if(get_data("SHOW TABLES LIKE '".$db_table_prefix."character_info'")){
    return false;
  }

    // run_sql("
    //   DROP TABLE `".$db_table_prefix."attribute_info`;
    // ");
    // run_sql("
    //   DROP TABLE `".$db_table_prefix."item_info`;
    // ");
    // run_sql("
    //   DROP TABLE `".$db_table_prefix."skill_info`;
    // ");
      
      run_sql("
          CREATE TABLE IF NOT EXISTS `".$db_table_prefix."character_info` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `title` varchar(50) NOT NULL,
            `code` char(32) NOT NULL,
            `is_his` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=his',
            `category` int(11) unsigned NOT NULL COMMENT '',
            `name_img` varchar(250) NOT NULL COMMENT '照片地址',
            `ud1` varchar(32) NOT NULL,
            `ud2` varchar(32) NOT NULL,
            `ud3` varchar(32) NOT NULL,
            `ud4` varchar(32) NOT NULL,
            `ud5` varchar(32) NOT NULL,
            `ud6` varchar(32) NOT NULL,
            `ud7` varchar(32) NOT NULL,
            `ud8` varchar(32) NOT NULL,
            `ud9` varchar(32) NOT NULL,
            `create_date` char(20) NOT NULL,
            `modify_date` char(20) NOT NULL,
            `parent_id` int(11) unsigned NOT NULL DEFAULT '0',
            `sort` tinyint(4) unsigned NOT NULL DEFAULT '99',
            PRIMARY KEY (`id`),
            UNIQUE KEY `code` (`code`)
          ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
      ");

      $uuid = kis_uuid();
      $cf_now = date('Y-m-d H:i:s');
      $tmp_sql ='INSERT INTO `'.$db_table_prefix.'character_info`(`title`, `code`, `is_his`, `category`, `name_img`, `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9`, `create_date`, `modify_date`) VALUES (?s,?s,?i,?s,?s,?s,?s,?s,?s,?s,?s,?s,?s,?s,?s,?s) ';
      $name_img='http://imgsrc.baidu.com/forum/w%3D580/sign=83b8109b57e736d158138c00ab514ffc/ccc597061d950a7b39be108309d162d9f3d3c938.jpg';
      $tmp_sql = prepare($tmp_sql ,array('admin',$uuid,0,'category',$name_img,'ud1','ud2','ud3','ud4','ud5','ud6','ud7','ud8','ud9',$cf_now,$cf_now) );
      // echo $tmp_sql;
      run_sql($tmp_sql);

      run_sql("
          CREATE TABLE IF NOT EXISTS `".$db_table_prefix."attribute_info` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `title` varchar(50) NOT NULL,
            `value` varchar(50) NOT NULL,
            `is_his` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=his',
            `category` int(11) unsigned NOT NULL COMMENT '',
            `uid` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'character_id',
            `sort` tinyint(4) unsigned NOT NULL DEFAULT '99',
            PRIMARY KEY (`id`)
          ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
      ");
      run_sql("
ALTER TABLE  `".$db_table_prefix."attribute_info` ADD  `ud1` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ;
ALTER TABLE  `".$db_table_prefix."attribute_info` ADD  `ud2` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ;
ALTER TABLE  `".$db_table_prefix."attribute_info` ADD  `ud3` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ;
");
      run_sql("
INSERT INTO `".$db_table_prefix."attribute_info` ( `id`,`title`, `value`, `is_his`, `category`, `uid`, `sort`) VALUES ( NULL,'职业', '军师', '0', '1', '1', '1');
      ");
      run_sql("
INSERT INTO `".$db_table_prefix."attribute_info` (`id`, `title`, `value`, `is_his`, `category`, `uid`, `sort`) VALUES (NULL, '统帅', '10', '0', '1', '1', '1')
, (NULL, '武力', '5', '0', '1', '1', '3')
, (NULL, '智力', '20', '0', '1', '1', '3')
, (NULL, '政治', '5', '0', '1', '1', '3')
, (NULL, '魅力', '60', '0', '1', '1', '3');
      ");

      run_sql("
          CREATE TABLE IF NOT EXISTS `".$db_table_prefix."item_info` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `title` varchar(50) NOT NULL,
            `desc` varchar(150) NOT NULL,
            `number` int(11) unsigned NOT NULL,
            `ud1` varchar(32) NOT NULL,
            `ud2` varchar(32) NOT NULL,
            `ud3` varchar(32) NOT NULL,
            `is_his` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=his',
            `category` int(11) unsigned NOT NULL COMMENT '',
            `uid` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'character_id',
            `sort` tinyint(4) unsigned NOT NULL DEFAULT '99',
            PRIMARY KEY (`id`)
          ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
      ");

      run_sql("
INSERT INTO `".$db_table_prefix."item_info` (`id`, `title`, `desc`, `number`, `ud1`, `uid`) 
VALUES (NULL, '空间', '', 53, '100', '1')
, (NULL, '人口', '', 10, '100', '1')
, (NULL, '农业', '', 0, '10', '1')
, (NULL, '商业', '', 0, '10', '1')
, (NULL, '技术', '', 0, '10', '1')
, (NULL, '金钱', '', 0, '', '1')
, (NULL, '粮食', '', 0, '', '1');
      ");


      run_sql("
          CREATE TABLE IF NOT EXISTS `".$db_table_prefix."skill_info` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `title` varchar(50) NOT NULL,
            `desc` varchar(150) NOT NULL,
            `number` int(11) unsigned NOT NULL,
            `ud1` varchar(32) NOT NULL,
            `ud2` varchar(32) NOT NULL,
            `ud3` varchar(32) NOT NULL,
            `is_his` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=his',
            `category` int(11) unsigned NOT NULL COMMENT '',
            `uid` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'character_id',
            `sort` tinyint(4) unsigned NOT NULL DEFAULT '99',
            PRIMARY KEY (`id`)
          ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
      ");

      run_sql("
INSERT INTO `".$db_table_prefix."skill_info` (`id`, `title`, `desc`, `number`, `ud1`, `uid`) 
VALUES (NULL, '小民房', '', 15, '1', '1')
, (NULL, '小型仓库', '', 1, '1', '1')
, (NULL, '村议会', '', 1, '2', '1')
, (NULL, '耕地', '', 7, '2', '1');
      ");

}

function init_map_db_info($db_table_prefix){

  // return false;
  // run_sql("
  //   DROP TABLE `".$db_table_prefix."map_info`;
  // ");

  //初始化数据库
  if(get_data("SHOW TABLES LIKE '".$db_table_prefix."map_info'")){
    return false;
  }
      
  run_sql("
      CREATE TABLE IF NOT EXISTS `".$db_table_prefix."map_info` (
        `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
        `title` varchar(50) NOT NULL,
        `code` char(32) NOT NULL,
        `is_his` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=his',
        `category` int(11) unsigned NOT NULL COMMENT '地图大类',
        `thumbnail_id` int(11) unsigned NOT NULL COMMENT '缩略图',
        `block_id` int(11) unsigned NOT NULL default '0',
        
        `path_id` int(11) unsigned NOT NULL COMMENT '通路',
        `door_id` int(11) unsigned NOT NULL COMMENT '大门入口',

        `bg_img` varchar(250) NOT NULL COMMENT '背景地址',
        `pos_x` int(11) unsigned NOT NULL,
        `pos_y` int(11) unsigned NOT NULL,        

        `ud1` varchar(32) NOT NULL  COMMENT '地形',
        `ud2` varchar(32) NOT NULL,
        `ud3` varchar(32) NOT NULL,
        `ud4` varchar(32) NOT NULL,
        `ud5` varchar(32) NOT NULL,
        `ud6` varchar(32) NOT NULL,
        `ud7` varchar(32) NOT NULL,
        `ud8` varchar(32) NOT NULL,
        `ud9` varchar(32) NOT NULL,
        `create_date` char(20) NOT NULL,
        `modify_date` char(20) NOT NULL,
        `parent_id` int(11) unsigned NOT NULL DEFAULT '0',
        `sort` tinyint(4) unsigned NOT NULL DEFAULT '99',
        PRIMARY KEY (`id`),
        UNIQUE KEY `code` (`code`)
      ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
  ");

  $pos_x=1000;
  $pos_y=1000;
  $base_sql ='INSERT INTO `'.$db_table_prefix.'map_info`(`title`, `code`, `is_his`, `category`, `pos_x`,`pos_y`, `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9`, `create_date`, `modify_date`) VALUES (?s,?s,?i,?i,?i,?i,?s,?s,?s,?s,?s,?s,?s,?s,?s,?s,?s) ';

  $opt_cat=array('cat1_min'=>2,'cat1_max'=>4,'cat1_count'=>0,'cat1_maxcount'=>6);

  $step = 24;
  for ($x=-1*($step); $x < 1+$step; $x++) { 
    for ($y=-1*($step); $y < 1+$step; $y++) { 
      if(check_cell_is_exists($x,$y,$db_table_prefix)!=true){
        $pos_x=1000+$x;
        $pos_y=1000+$y;
        $uuid = kis_uuid();
        $cf_now = date('Y-m-d H:i:s');
        if(intval($pos_x)==1000 && intval($pos_y)==1000){
          $title = 'CAMP';
          $category = 0;
        }else{
          $title = 'pos:'.$pos_x.','.$pos_y;
          $category = rand_map_category($opt_cat,$x,$y);  
        }        
        $tmp_sql = prepare($base_sql ,array($title,$uuid,0,$category,$pos_x,$pos_y,'ud1','ud2','ud3','ud4','ud5','ud6','ud7','ud8','ud9',$cf_now,$cf_now) );
        // echo $tmp_sql;
        run_sql($tmp_sql);
      }
    }
  }

}

function check_cell_is_exists($x,$y,$db_table_prefix){
  // return false;

  $base_sql ='SELECT * FROM `'.$db_table_prefix.'map_info` WHERE `is_his`=?i AND `parent_id`=?i AND `pos_x`=?i AND `pos_y`=?i LIMIT 1 ';

    $tmp_sql = prepare($base_sql ,array(0,0,$x,$y) );
    // echo $tmp_sql;
    $ret_map =get_line($tmp_sql);
    if($ret_map!==false && isset($ret_map[''])){
        return true;
    }else{
      return false;  
    }
}

function rand_map_category(&$opt_cat,$x,$y){
  global $debugMode, $time_log , $c,$a, $outVar;
  global $db_table_prefix;

  $ret=3; //未知区域
  $x1 = abs($x);
  $y1 = abs($y);
  $z = sub_rand_map_category($opt_cat,$x,$y);

  return $z;

  if($debugMode){
    $time_log .= date('Y-m-d H:i:s') . ' ' . __FUNCTION__. '(,'.$x.','.$y.') get:'.$z .PHP_EOL;
  }

  for ($i=1; $i <=4 ; $i++) {
    if(isset($opt_cat['cat'.$i.'_min']) ){
      $tt = intval($opt_cat['cat'.$i.'_min']);
      if($x1<$tt){
        if($debugMode){
          $time_log .= '---- i='.$i . __FUNCTION__. '(,'.$x.','.$y.') #1'.PHP_EOL;
        }
        return $ret;
      }else if($y1<$tt){
        if($debugMode){
          $time_log .= '---- i='.$i. __FUNCTION__. '(,'.$x.','.$y.') #2'.PHP_EOL;
        }
        return $ret;
      }
    }
    if(isset($opt_cat['cat'.$i.'_max']) ){
      $tt = intval($opt_cat['cat'.$i.'_max']);
      if($x1>$tt){
        if($debugMode){
          $time_log .= '---- i='.$i . __FUNCTION__. '(,'.$x.','.$y.') #3'.PHP_EOL;
        }
        return $ret;
      }else if($y1>$tt){
        if($debugMode){
          $time_log .= '---- i='.$i . __FUNCTION__. '(,'.$x.','.$y.') #4'.PHP_EOL;
        }
        return $ret;
      }
    }
  
    if(intval($z)==intval($i) ) {
      if(isset($opt_cat['cat'.$i.'_maxcount']) ){
        $tt = intval($opt_cat['cat'.$i.'_count']);
        $ttmax = intval($opt_cat['cat'.$i.'_maxcount']);
        if($tt>=$ttmax){
          if($debugMode){
            $time_log .= '---- i='.$i . __FUNCTION__. '(,'.$x.','.$y.') #5'.PHP_EOL;
          }
          return $ret;
        }else{
          $opt_cat['cat'.$i.'_count'] = $tt+1;
        }
      }
    }
  }
}

function sub_rand_map_category(&$opt_cat,$pos_x,$pos_y){
  // $x=_rnd(0,$pos_x);
  // $y=_rnd(0,$pos_y);
  $z = _rnd(1,100);
  if ($z>95){
    return 4;   //枯竭区域
  }else if ($z>80){
    return 2;   //安全区域
  }else if ($z>75){
    return 1;   //遗迹区域
  }else{
    return 3;   //未知区域
  }
}



function list_all_map(){
    global $debugMode, $time_log , $c,$a, $outVar;
    global $db_table_prefix;

    $adminMode = 0;
    $outVar['adminMode']=0;
    if($_SESSION['level'] >= 3){
          $adminMode=1;
          //$outVar['adminMode']=1;
    }else{
      $tt = intval(v('adm'))  ;
      if ($tt>0 ){
          $adminMode=1;
          $outVar['adminMode']=1;
      }
    }

    $homePosX=1000;
    $homePosY=1000;
    $step=3;
    $tt = intval(v('step'));    
    if ($tt>0){
        $step = $tt;
    }
    $tt2 = intval(v('posx'));
    if ($tt2>0 && $tt2 <10000){
        $homePosX=$tt2;
    }
    $tt2 = intval(v('posy'));
    if ($tt2>0 && $tt2 <10000){
        $homePosY=$tt2;
    }

    $cell_height = '50px';
    $cell_width = '50px';

    $x1=$homePosX-$step;
    $x2=$homePosX+$step;
    $y1=$homePosY-$step;
    $y2=$homePosY+$step;

    $base_sql ='SELECT * FROM `'.$db_table_prefix.'map_info` WHERE `is_his`=?i AND `parent_id`=?i AND `pos_x`>=?i AND `pos_x`<=?i AND `pos_y`>=?i AND `pos_y`<=?i ORDER BY `pos_x`,`pos_y` LIMIT 0 , 500 ';

    $tmp_sql = prepare($base_sql ,array(0,0,$x1,$x2,$y1,$y2) );
    // echo $tmp_sql;
    $ret_map =get_data($tmp_sql);
    if($ret_map==false){
        return 'MAP NOT READY !!!';
    }

    $x1=$homePosX;
    $x2=$homePosX;
    $y1=$homePosY;
    $y2=$homePosY;
    $map_xy=array();
    foreach ($ret_map as $key => $value) {
        if(isset($value['pos_x']) && isset($value['pos_y'])){
            $x_t = intval($value['pos_x']);
            $y_t = intval($value['pos_y']);
            if($x_t<$x1) {
                $x1=$x_t;
            }else if($x_t>$x2){
                $x2=$x_t;
            }
            if($y_t<$y1) {
                $y1=$y_t;
            }else if($y_t>$y2){
                $y2=$y_t;
            }
            $map_xy['x'.$x_t.'y'.$y_t]=$value;
        }
    }

    $td_s='<td width="'.$cell_width.'" ';
    $map_html = '<h3>MAP </h3>';

    $map_html .='<table id="maptable" align="center" border="1" cellspacing="0" cellpadding="0" class="printtab"><tbody>'.PHP_EOL;
    
    $map_html .= '<tr height="'.$cell_height.'">'.PHP_EOL;
    $map_html .= $td_s .'id="xytd">&nbsp;</td>'.PHP_EOL;
    for ($i=$x1; $i <= $x2; $i++) { 
      $map_html .= '<td width="'.$cell_width.'" id="xtd_'.$i.'">x:'.$i.'</td>'.PHP_EOL;
    }
    $map_html .= '</tr>'.PHP_EOL;

    for($y = $y1; $y <=$y2; $y++ ){
        $map_html .= '<tr height="'.$cell_height.'">'.PHP_EOL;
        
        $map_html .= $td_s .'id="ytd_'.$y.'">y:'.$y.'</td>'.PHP_EOL;

        for($x=$x1; $x <=$x2; $x++ ){
            $v='';
            $map_id='';
            $title ='';
            $style='';
            if(isset($map_xy['x'.$x.'y'.$y])){
                $cell = $map_xy['x'.$x.'y'.$y];
                $c=get_cell_color_by_cat($cell['category']);
                $style=' style="background-color:#'.$c.'" ';

                $title = get_desc_by_cat($cell['category']);
                $title = ' title="' . $title . '" ';
                $title .= ' cat-'.$cell['category'] . ' ';
                                
                $v = $cell['title'];
                if($adminMode){
                    $href = '?c=map&a=form&adm=1&code='.$cell['code'].'&debug=1';
                    if(!empty($cell['bg_img']) && stripos($cell['bg_img'], ':/')==false){
                        $tmp_t = $cell['bg_img'];
                        if(strlen($tmp_t)>6){
                            $tmp_t = csubstr($tmp_t,0,6).'...';
                        }
                    }else{
                        $tmp_t = '区域';
                    }
                    $tmp_v = get_desc($cell);
                    $tmp_v = get_link($href,$tmp_t,$tmp_v);
                    $v = str_ireplace("pos:", $tmp_v .'<br/>', $v);
                }else if($debugMode){
                  $href = '?c=map&a=form&code='.$cell['code'].'&debug=1';
                  $tmp_v = get_link($href,'区域');
                  $v = str_ireplace("pos:", $tmp_v .'<br/>', $v);
                }else{
                  $v = str_ireplace(":", ':<br/>', $v);
                }                
                $map_id = $cell['code'];
            }
            
            $map_html .= $td_s .'id="td_'.$x.'_'.$y.'" mapid="'.$map_id.'" '.$style.$title.' >'.$v.'</td>'.PHP_EOL;
        }
        $map_html .= '</tr>'.PHP_EOL;
    }
    return $map_html.'</tbody></table>'.PHP_EOL;
}


function get_desc(&$cell){
    $ret = '';
    foreach ($cell as $key => $value) {
        if(!empty($value) && $key!=$value){
            if('bg_img'==$key){
                $ret .= '【'.$value . '】 ';    
            }else if(stripos('bg_img;ud1;ud2;ud3;ud4;ud5;ud6;ud7;ud8;ud9', $key)!==false){
                $ret .= $value . ';';    
            }
        }
    }
    return drop_last_char($ret);
}

function get_link($href,$title,$msg=''){
  if(!empty($msg)) $msg='title="'.$msg.'"';
  return '<a href="'.$href.'" '.$msg.' target="_blank">'.$title.'</a>'.PHP_EOL;
}

function get_cell_color_by_cat($cat){
    $cc = intval($cat);
    $c = 'aaaaaa';
    switch ($cc) {
      case 0:   //幸存者营地
          $c='008800';
          break;

      case 1:   //遗迹区域
          $c='e63f00';
          break;

      case 2:   //安全区域
          $c='99ff99';
          break;

      case 4:   //枯竭区域
          $c='ffffff';
          break;

      default:  //未知区域
          $c='aaaaaa';
          break;
    }
    return $c;
}

function get_desc_by_cat($cat){
    $cc = intval($cat);
    $c = 'UNKNOW';
    switch ($cc) {
      case 0:
          $c='幸存者营地';
          break;

      case 1:   //遗迹区域
          $c='遗迹区域';
          break;

      case 2:   //安全区域
          $c='安全区域';
          break;

      case 4:   //枯竭区域
          $c='枯竭区域';
          break;

      default:  //未知区域
          $c='未知区域';
          break;
    }
    return $c;
}



function list_one_map(){
    global $debugMode, $time_log , $c,$a, $outVar;
    global $db_table_prefix;

    $code = v('code');
    if(empty($code)){
      return '非法调用！';
    }

    $outVar['uuid'] = $code;

    $cell_height = '50px';
    $cell_width = '50px';
// `id`, `title`, `code`, `is_his`, `category`, `bg_img`, `pos_x`, `pos_y`, `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9`, `create_date`, `modify_date`, `parent_id`, `sort`
    $base_sql ='SELECT `title`, `code`, `category`, `bg_img`, `pos_x`, `pos_y`, `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9` FROM `'.$db_table_prefix.'map_info` WHERE `is_his`=?i AND `code`=?s LIMIT 0 , 1 ';

    $tmp_sql = prepare($base_sql ,array(0,$code) );
    // echo $tmp_sql;
    $ret_map =get_line($tmp_sql);
    if($ret_map==false){
        return 'MAP NOT READY !!!';
    }
    
    return json_encode($ret_map).PHP_EOL;
}

/**

    上面的是专为本app修改过的。下面的可能有些是没有用到的。

*/

function set_age_for_random_map_info($map_uuid,$age=0){
  $tmp_sql=<<<SQL
UPDATE `random_map_info` SET `parent_id`=?i , `modify_date`=?s , `ud2`=?s WHERE `code`=?s
SQL;
  
  $cf_now = date('Y-m-d H:i:s');
  if($age===0){
    //长期有效
    $tmp_sql = prepare($tmp_sql ,array(2,$cf_now, 0,$map_uuid) );
  }else{
    //有效期为 intval($age) 天
    $tmp_sql = prepare($tmp_sql ,array(3,$cf_now, intval($age),$map_uuid) );
  }
    return run_sql($tmp_sql);
}


function get_city_pic($n=null){
  $city_pic_arr=array();
  array_push($city_pic_arr, array('top_left' =>105 , 'top_right' =>106 ,'foot_left' =>121 , 'foot_right' =>122));
  array_push($city_pic_arr, array('top_left' =>107 , 'top_right' =>109 ,'foot_left' =>123 , 'foot_right' =>124));
  array_push($city_pic_arr, array('top_left' =>109 , 'top_right' =>110 ,'foot_left' =>125 , 'foot_right' =>126));
  array_push($city_pic_arr, array('top_left' =>111 , 'top_right' =>112 ,'foot_left' =>127 , 'foot_right' =>128));

  array_push($city_pic_arr, array('top_left' =>137 , 'top_right' =>138 ,'foot_left' =>153 , 'foot_right' =>154));
  array_push($city_pic_arr, array('top_left' =>139 , 'top_right' =>140 ,'foot_left' =>155 , 'foot_right' =>156));
  if($n!==null && isset($city_pic_arr[$n])){
    return $city_pic_arr[$n];
  }
  return _rnd(0,count($city_pic_arr)-1);
}

function get_village_pic($n=null){
  $pic_arr=array();
  array_push($pic_arr, array('top_left' =>169 , 'top_right' =>170));
  array_push($pic_arr, array('top_left' =>171 , 'top_right' =>172 ));
  array_push($pic_arr, array('top_left' =>173 , 'top_right' =>174 ));
  array_push($pic_arr, array('top_left' =>187 , 'top_right' =>188 ));
  array_push($pic_arr, array('top_left' =>189 , 'top_right' =>190 ));

  if($n===null) $n = _rnd(0,count($pic_arr)-1);
  if(isset($pic_arr[$n])){
    return $pic_arr[$n];
  }
  return $pic_arr[0];
}

function get_smaill_village_pic($n=null){
  $pic_arr=array();
  array_push($pic_arr, array('top_left' =>185 , 'top_right' =>0));
  array_push($pic_arr, array('top_left' =>186 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>175 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>191 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>187 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>188 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>189 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>190 , 'top_right' =>0 ));

  if($n===null) $n = _rnd(0,count($pic_arr)-1);
  if(isset($pic_arr[$n])){
    return $pic_arr[$n];
  }
  return $pic_arr[0];
}



//画地图
function map_div($x, $y, $v){
    global $w, $h, $path;

    $rd = 149;

    //if ( $y > 4 ) $v = 0;
    $k = $y * $w + $x;
    //if ( array_key_exists($k, $this->_enable) ) {
        //echo "<div class=\"grid cell_enable_{$this->_enable[$k]}\" style=\"";
    //} else {
        echo "<div class=\"grid tileBpic ";
        if($v==='*') {
            //70%是草地,其他事花朵
            $catArr=array(161,162,163,164,177,178,179,180,216,232,243);
            $jj = _rnd(0,100);
            if($jj<70){
                $tt = 2;
            }else{
                $tt = _rnd(0,count($catArr)-1);
            }            
            echo 'tileBpic_'.$catArr[$tt];
        }else{
            $catArr=array(89,181,168,184);  //树,枯木,石,矿
            $jj = _rnd(0,100);
            if($jj<90){
                $tt = 0;
            }else if($jj<95){
                $tt = 1;
            }else{                
                $tt = _rnd(0,count($catArr)-1);
            }
            echo 'tileBpic_'.$catArr[$tt];
        }        
        echo "\" style=\"";
    //}
    echo 'top:'. 35*$y.'px;';
    echo 'left:'. 35*$x.'px;';
    //if ($v & 1)
        //echo "border-top:1px solid #F5F5F5;";
    //if ($v & 2)
        //echo "border-right:1px solid #F5F5F5;";
    //if ($v & 4)
        //echo "border-bottom:solid 1px #F5F5F5;";
    //if ($v & 8)
        //echo "border-left:solid 1px #F5F5F5;";
    if ( in_array($y * $w + $x, $path) )
        echo "color:red;";
    echo '">';
    // echo $y * $w + $x;
    // if($v==='*') {
    //     echo '.';
    //     //163
    // }else{
    //     echo '#';
    //     //89
    // }
    echo '</div>'."\n";
}

//画地图
function div2($x, $y, $v){
    global $w, $h, $path;
    //if ( $y > 4 ) $v = 0;
    $k = $y * $w + $x;
    //if ( array_key_exists($k, $this->_enable) ) {
        //echo "<div class=\"grid cell_enable_{$this->_enable[$k]}\" style=\"";
    //} else {
        echo "<div class=\"grid \" style=\"";
    //}
    echo 'top:'. 10*$y.'px;';
    echo 'left:'. 10*$x.'px;';
    //if ($v & 1)
        //echo "border-top:1px solid #F5F5F5;";
    //if ($v & 2)
        //echo "border-right:1px solid #F5F5F5;";
    //if ($v & 4)
        //echo "border-bottom:solid 1px #F5F5F5;";
    //if ($v & 8)
        //echo "border-left:solid 1px #F5F5F5;";
    if ( in_array($y * $w + $x, $path) )
        echo "color:red;";
    echo '">';
    // echo $y * $w + $x;
    if($v==='*') {
        echo '.';
        //163
    }else{
        echo '#';
        //89
    }
    echo '</div>'."\n";
}

function isInRoadArr($k,$roadpath){
    if($roadpath && is_array($roadpath)){
        foreach($roadpath as $roadSetId=>$roadSetArr){
            if(is_array($roadSetArr)){
                if ( in_array($k, $roadSetArr) ){
                    // return $roadSetId;
                    return array('id'=>$roadSetId,'title'=>$roadSetArr[0]);
                    // break;
                }    
            }else{
                if($k === $roadSetArr){
                    return array('id'=>$roadSetId,'title'=>$roadSetArr[0]);
                }
            }
            
        }    
    }    
    return false;
}


function get_base_color_arr(){
  $colorArr=array('#666666','#66CCCC','#CCFF66','#FF99CC','#FFCC00','#009999','#CC3333','#666699','#CCFF99','#FF9900');
  $len = count($colorArr);
  $first_color=$colorArr[_rnd(0,$len-1)];
  $ret=array($first_color);
  foreach ($colorArr as $cc) {
    if($cc !==$first_color){
      $ret[] = $cc;
    }
  }
  return $ret;
}

$base_color_arr=null;

// 画随机地图方法
function map_div_debug($x, $y, $v){  
  global $w, $h, $path, $roadpath;
  global $base_color_arr;

  if($base_color_arr==null){
    $base_color_arr = get_base_color_arr();
  }

  $ret_html = '';

  $k = $y * $w + $x;
  $roadSetId=isInRoadArr($k,$roadpath);
  $nodeSetID=false;
  $len = count($path);
  foreach ($path as $tmpid=>$tmpArr) {
    if ($tmpArr)
    if ( in_array($k, $tmpArr) ){
      $nodeSetID=$tmpid;
      break;
    }
  }
  $div_id = 'div_'.$x.'_'.$y;
  if($roadSetId!==false){
    $ret_html .= "<div id=\"".$div_id."\" class=\"grid  \" style=\"";
  }else{
    $ret_html .= "<div id=\"".$div_id."\"class=\"grid cell_{$v}\" style=\"";
  }

  $ret_html .= 'top:'. 34*$y.'px;';
  $ret_html .= 'left:'. 34*$x.'px;';

  //echo '/* k:'.$k.' */';
  $inNodeSetFlag=false;
  $len = count($path);
  $colorArr=$base_color_arr;
  foreach ($path as $tmpid=>$tmpArr) {
    if ($tmpArr)
    if ( in_array($k, $tmpArr) ){      
      $id = fmod(intval($tmpid),count($colorArr));
      $ret_html .= "background-color:".$colorArr[$id].';';
      $inNodeSetFlag=true;
      break;
    }
  }
  if($inNodeSetFlag===false){
    if ( in_array($k, $roadpath) ){
      $ret_html .= 'background-color:#CCCCCC;';
    }
  }
  $ret_html .= '">';
  if($inNodeSetFlag===false && $roadSetId!==false){
    $tmpHtml='R:'.$roadSetId['id'];
    // $tmpHtml=$k;
    $tmpTitle = '#'.$k."\n".$roadSetId['title']."\n".'rd:'.$roadSetId['id'];
    $ret_html .= '<a href="javascript:void(0);" title="'.$tmpTitle.'">'.$tmpHtml.'</a>';
  }else{
    $ret_html .= $k;
  }
  // echo $y * $w + $x;
  // echo $v;
  $ret_html .= '</div>'."\n";
  return $ret_html;
}


function gen_new_map(){
	global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
	global $debugMode, $time_log;

  $max = 1000;
	$tt = intval(v('w'))  ;
    if ($tt>0 && $tt<=$max){
        $w=$tt;
    }else{
        die('403 Access Denied/Forbidden');
    }

    $tt = intval(v('h'))  ;
    if ($tt>0 && $tt<=$max){
        $h=$tt;
    }else{
        die('403 Access Denied/Forbidden');
    }


    //初始化数据库
    init_db_random_map_info();

    $tt = intval(v('d'))  ;
    if ($tt>0 && $tt<100){
        $density=$tt;
    }

    $ksRndMap = new kisRandomMap();
    $aStar = new AStar();

    $endId = ($w * $h)-1;

    // $time_log.= "基础加载时间: ". used_time($pagestartime) ."秒.<br/>".PHP_EOL; 
    $time1=microtime(); 

    $ksRndMap->set($w, $h);
    $ksRndMap->create();
    // $grids = $ksRndMap->get();
    $ksRndMap->setDensity($density);
    // $ksRndMap->setCA(4,5);
    $ksRndMap->run_ca();

    if($debugMode) $ksRndMap->set_debug(1);
    if($debugMode) echo '<!--';
    $tmpNodeSet=$ksRndMap->debug_walk();
    $grids = $ksRndMap->get();
    // var_dump($grids);
    $baseNodeSet=$ksRndMap->debug_nodeSet();
    if($debugMode) echo '-->';
    $time_log.= "maze->create 时间: ". used_time($time1) ."秒.<br/>".PHP_EOL; 
    $time2=microtime(); 

    // $path=$tmpNodeSet;
    $path=array();
    $roadpath=array();
    foreach ($baseNodeSet as $value) {
        array_push($path,$value);
    }

    // 寻路
    $aStar->set($w, $h, $grids);
    // $path = $aStar->search(0, $endId);       // 从零开始找到35
    $roadArr=$ksRndMap->get_road();
    // var_dump($roadArr);
    foreach ($roadArr as $road) {
        $roadInfo=$ksRndMap->getRoadByNodeSet($road['from'],$road['to'],$baseNodeSet);
        $pos1 = $roadInfo['from'];
        $pos2 = $roadInfo['to'];
        $tmpPath=array();
        $tmpPath = $aStar->search($pos1, $pos2);
        // if($debugMode) {
        //     echo '--path array,#'.$pos1.'-#'.$pos2.':'.implode(',',$tmpPath) .PHP_EOL.PHP_EOL.PHP_EOL; 
        // }
        $tmpPath2=array();
        array_push($tmpPath2,'road_'.$pos1.'_'.$pos2);
        foreach ($tmpPath as $roadPos) {
            if($roadPos!==$pos1 && $roadPos!==$pos2){
                array_push($tmpPath2,$roadPos);
            }
        }
        $tmpPath2 = fix_roadPath($tmpPath2);
        array_push($roadpath,$tmpPath2);    
    }
    //array_push($path,$roadpath);
    // var_dump($roadpath);
    $time_log.= "aStar->search 时间: ". used_time($time2) ."秒.<br/>".PHP_EOL; 

    $mapJson = array();
    $mapJson['map'] = $ksRndMap->getMapJsonObj();
    $mapJson['road'] = $roadpath;
    $mapJson['path'] = $path;

    return $mapJson;
}

function save_random_map_info($mapJson,$code,$options_arr=null){
	global $debugMode, $time_log;
    //REPLACE INTO
    //INSERT INTO
    $tmp_sql=<<<SQL
INSERT INTO `random_map_info`( `title`, `code`, `is_his`, `category`, 
    `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9`,
    `create_date`, `modify_date`, `admin_uid`, `owner_uid`, `json_text`, `parent_id`, `sort`)
     VALUES (?s,?s,?i,?s,   ?s,?s,?s,?s,?s,?s,?s,?s,?s,    ?s,?s,?s,?s,?s,?i,?i )
SQL;
    $cf_now = date('Y-m-d H:i:s');
    
    $opt_arr=array(
        'ud1'=>''       //存储格式，是否是压缩的
        ,'ud2'=>''      //有效期天数      
        ,'ud3'=>'0'      //地图格式  1=地牢
        ,'ud4'=>''      //地图大小
        ,'ud5'=>''
        ,'ud6'=>''
        ,'ud7'=>''
        ,'ud8'=>''
        ,'ud9'=>'');

    if($options_arr && is_array($options_arr)){
        foreach ($options_arr as $key => $value) {
            $opt_arr[$key]=$value;
        }   
    }

    $json_text = json_encode($mapJson);
    $len_source = max_len($json_text);
    $len_gzcompress = 0;
    if($len_source>500){
        $opt_arr['ud1']=1;
        $json_text = gzcompress($json_text,9);
        $json_text = urlencode($json_text);
        $len_gzcompress = max_len($json_text);
    }    
    $json_text = addslashes( $json_text ); 

    // if($debugMode) 
    //     echo '<br/>$$$$ '.$row_data.PHP_EOL;

    $tmp_sql = prepare($tmp_sql ,array($code, $code, 0, 'tmp',
        $opt_arr['ud1'], $opt_arr['ud2'], $opt_arr['ud3'], $opt_arr['ud4'], $opt_arr['ud5'], 
            $opt_arr['ud6'], $opt_arr['ud7'], $opt_arr['ud8'], $opt_arr['ud9'],
        $cf_now , $cf_now,'admin', 'admin', $json_text,1,1
        ) );

    if($debugMode){
        // echo '<br/>-- '.$tmp_sql.PHP_EOL;
        $time_log .= 'len_source='.$len_source.PHP_EOL;
        $time_log .= 'len_gzcompress='.$len_gzcompress.PHP_EOL;

        if($len_gzcompress) {
            $tt1 = $len_source-$len_gzcompress;
            $tt2 = $tt1 / $len_source ; 
            $time_log .= 'save :'.$tt1.'B, '.$tt2.'%'.PHP_EOL;
        }
    }

    return run_sql($tmp_sql);	
}


function reload_map($map_uuid){
	global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
	global $debugMode, $time_log;


  //初始化数据库
  init_db_random_map_info();

  $tmp_sql=<<<SQL
SELECT * FROM `random_map_info` WHERE `code`=?s AND `is_his`=?i 
SQL;
    $tmp_sql = prepare($tmp_sql ,array($map_uuid, 0) );

    // if($debugMode) echo '<br/>-- '.$tmp_sql.PHP_EOL;

    $ret =get_data($tmp_sql);

    if(!isset($ret['map'])) $ret = $ret[0];
    // var_dump($ret);

    if(isset($ret['parent_id']) && isset($ret['create_date']) && isset($ret['modify_date']) ){
        if(intval($ret['parent_id'])==1 ){   //临时
            set_age_for_random_map_info($map_uuid,7);  //非临时，有效期为15 day

        }else if (intval($ret['parent_id'])==2 ){    //长期有效
            //skip
        }else{
            $cd = $ret['create_date'];
            $md = $ret['modify_date'];
            $cf_now = date('Y-m-d H:i:s');  //2014-11-10 15:18:32

            // 判断是否大于30分钟 (1800秒)
            if( strtotime($cf_now) - strtotime($md) > 1800 ){   
                //初次修改后，超过30分钟，再修改
                if(intval($ret['parent_id'])==3 && substr($cd, 0,10)!=substr($md, 0,10) ) {
                    set_age_for_random_map_info($map_uuid,90);
                }else{
                    set_age_for_random_map_info($map_uuid,15);
                }
            }
        } 
    }    

    $ksRndMap = new kisRandomMap();
    $aStar = new AStar();
    
    // var_dump($ret['json_text']);
    // $json = safe_json_str_decode($ret['json_text']);
    $json = stripslashes($ret['json_text']);
    if(trim($ret['ud1'])=='1'){
        $json=urldecode($json);
        $json=gzuncompress($json);
    }
    // var_dump($json);
    // echo '=========================='.PHP_EOL;
    // $jsonObj = json_decode($ret['json_text']);
    // var_dump($jsonObj);

    $jsonObj = json_decode($json,true);
    // var_dump($jsonObj);

    if(trim($ret['ud3'])=='1'){
      //dungeon
      // $jsonObj = fix_dungeon_map_for_reload($ret,$jsonObj);
    }

    $map = $ksRndMap->recoveryMap($jsonObj['map']);
    // var_dump($map);
    $w = $map['_w'];
    $h = $map['_h'];
    $density = $map['_density'];
    $grids = $map['_grids'];   

    $path=array();
    $path = $jsonObj['path'];
    $roadpath = $jsonObj['road'];

    // // var_dump($roadpath);
    // $tmpPath = $roadpath[count($roadpath)-1];
    // // var_dump($tmpPath);
    // $tmpPath = fix_roadPath($tmpPath);
    // // var_dump($tmpPath);
    $roadpathNew=array();
    for ($i=0; $i <count($roadpath); $i++) { 
        array_push($roadpathNew,fix_roadPath($roadpath[$i]));
    }
    // array_push($roadpathNew,$tmpPath);
    $roadpath=$roadpathNew;
    $roadpathNew=null;
    // // var_dump($roadpath);

    // var_dump($path);
    $baseNodeSet = $map['_nodeSet'];
    $tmpNodeSet = $map['_nodeTmpSet'];
    // var_dump($baseNodeSet);
    // var_dump($tmpNodeSet);
}

function check_pos_top_val_in_check_arr($v,$val){
    $arr = explode(';', $v);
    $check = explode(';', $val);

  foreach ($arr as $key => $value) {
    if(stripos($value, '#')!==false){
      $arr2 = explode('#', $value);
      $cc = $arr2[count($arr2)-1];
      foreach ($check as $checkvalue) {
          if($cc===$checkvalue) return true;
      }      
    }
  }
  return false;
}

function convert_map_grids($grids,$w ,$h,$color_config){
    $debugMode = get_func_debug_mode(__METHOD__);
    if($debugMode) {
        echo 'DEBUG: ' . __METHOD__ . '()'. PHP_EOL; 
        echo print_r($grids,true);
    }

    // $color_config = array('leaf'=>'5','room'=>'1','hall'=>'1','base'=>'5');
    // $color_config['sort'] = 'hall;room;leaf;base';
    $check = $color_config['room'] . ';' . $color_config['hall'];
    $ret_arr = array();
    for($y = 0; $y < $h; $y++ ){
        for($x=0; $x < $w; $x++ ){
            $v = $grids[$y * $w + $x];
            if(check_pos_top_val_in_check_arr($v,$check)){
                $grids[$y * $w + $x] = '*';
            }else{
                $grids[$y * $w + $x] = 0;
            }
        }
    }

    if($debugMode) {
        echo 'DEBUG: ' . __METHOD__ . '() process end .'. PHP_EOL; 
        echo print_r($grids,true);
    }
    return $grids;
}

// function fix_dungeon_map_for_reload(&$ret,$jsonObj){
//     $debugMode = get_func_debug_mode(__METHOD__);
//     if($debugMode) {
//         echo 'DEBUG: ' . __METHOD__ . '()'. PHP_EOL; 
//         echo print_r($ret,true);
//         echo print_r($jsonObj,true);
//     }
// }

function gen_show_html($pagestartime,$is_dungeon=0){
    global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
    global $debugMode, $time_log;

    $map_html='';
    for($y = 0; $y < $h; $y++ ){
        for($x=0; $x < $w; $x++ ){
            $v = $grids[$y * $w + $x];
            if($debugMode) {
              $map_html .= map_div_debug($x, $y, $v, $is_dungeon);
            }else{
              $map_html .= map_div($x, $y, $v, $is_dungeon);
            }
        }
    }

    $time_log.= "页面运行时间: ". used_time($pagestartime) ."秒.<br/>".PHP_EOL; 

    return $map_html;
}


function debug_showNodeSetInfo(){
	global $debugMode, $baseNodeSet, $tmpNodeSet;
	if(!$debugMode) return '';

	$ret = '';
    $ret .= '<!--'.PHP_EOL;
    if(is_array($baseNodeSet)){
        foreach ($baseNodeSet as $tmpSetId => $tmpSetArr) {
            if(is_array($tmpSetArr)){
                $ret .= '#'.$tmpSetId.'='.implode(',',$tmpSetArr) .PHP_EOL;    
            }else{
                $ret .= '#'.$tmpSetId.'='.$tmpSetArr .PHP_EOL;
            }
        }
        $ret .= '========================================='.PHP_EOL;
    }	    
    if(is_array($tmpNodeSet)){
        foreach ($tmpNodeSet as $tmpSetId2 => $tmpSetArr2) {
            if(is_array($tmpSetArr2)){
                $ret .= '#'.$tmpSetId2.'='.implode(',',$tmpSetArr2) .PHP_EOL;
            }else{
                $ret .= '#'.$tmpSetId2.'='.$tmpSetArr2 .PHP_EOL;
            }  
        }
    }	    
    $ret .= '-->'.PHP_EOL;

	return $ret;
}


function fix_roadPath($tmpPath){        
    return $tmpPath;        //FIXME @141111

    global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
    global $debugMode, $time_log;
    $tmpPathNew = array();
/*
1，非直线
*/
    // var_dump($tmpPath);
    $l = count($tmpPath);
    if($l<6) {
        // if($debugMode){
        //     echo 'DEBUG: '.__FUNCTION__.'()  road len='.$l.PHP_EOL;
        // }
        return sort($tmpPath);
    }

    $fixTimes=0;
    $lastFixId=null;
    for ($i=3; $i <$l; $i++) {         
        if($fixTimes==0 && $tmpPath[$i]==$tmpPath[$i-1]+1 && $tmpPath[$i]==$tmpPath[$i-2]+2 && $tmpPath[$i]==$tmpPath[$i-3]+3){
            //当前为横排第四个
            // if($debugMode){
            //     echo 'DEBUG: '.__FUNCTION__.'() #'.$tmpPath[$i].'<br/>'.PHP_EOL;
            // }
            $jj = _rnd(1,100);
            if($jj<45){
                if($debugMode){
                    echo 'DEBUG: '.__FUNCTION__.'() #'.$tmpPath[$i].'<br/>'.PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1#'.($tmpPath[$i]+$w).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1#'.($tmpPath[$i]+$w-1).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1#'.($tmpPath[$i]+$w-2).'<br/>'.PHP_EOL;
                }
                array_push($tmpPathNew,$tmpPath[$i]+$w);
                array_push($tmpPathNew,$tmpPath[$i]+$w-1);
                array_push($tmpPathNew,$tmpPath[$i]+$w-2);
                $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-1);
                $fixTimes++;

                $arrkey = array_search(($tmpPath[$i]-3), $tmpPathNew);
                if($debugMode){
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1# check'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                }
                if ($arrkey !== false){
                    if($debugMode){
                        echo 'DEBUG: '.__FUNCTION__.'() mode 1# exist'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 1# del'.($tmpPath[$i]-2).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 1# del'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                    }
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-2);
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-3);
                }

            }else if($jj<75){
                if($debugMode){
                    echo 'DEBUG: '.__FUNCTION__.'() #'.$tmpPath[$i].'<br/>'.PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 2# add'.($tmpPath[$i]-$w).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 2# add'.($tmpPath[$i]-$w-1).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 2# add'.($tmpPath[$i]-$w-2).'<br/>'.PHP_EOL;                    
                }
                array_push($tmpPathNew,$tmpPath[$i]-$w);
                array_push($tmpPathNew,$tmpPath[$i]-$w-1);
                array_push($tmpPathNew,$tmpPath[$i]-$w-2);
                $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-1);
                $fixTimes++;

                $arrkey = array_search(($tmpPath[$i]-$w-3), $tmpPathNew);
                if ($arrkey !== false){
                    if($debugMode){
                        echo 'DEBUG: '.__FUNCTION__.'() mode 2# exist'.($tmpPath[$i]-$w-3).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 2# del'.($tmpPath[$i]-2).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 2# del'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                    }
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-2);
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-3);
                }

            }
            $lastFixId=$i;
            array_push($tmpPathNew,$tmpPath[$i]);
 
        }else{
            if($lastFixId && $i-$lastFixId>5) {
                $fixTimes=0;
                $lastFixId=null;
            }
            array_push($tmpPathNew,$tmpPath[$i]);
        }
    }
    

    // $tmpId=0;
    // $lastArr = array();
    // foreach ($tmpPath as $path_key => $path_value) {
    //     $flag = false;
    //     $tmpArr = array();
    //     $tmpArr['x'] = $ksRndMap->getNodeX($path_value);
    //     $tmpArr['y'] = $ksRndMap->getNodeY($path_value);
    //     $lastArr[$path_key] = $tmpArr;

        // if(!isset($lastArr['x'])) {
        //     $lastArr['x'] = $ksRndMap->getNodeX($path_value);
        //     $lastArr['x_count'] = 0;
        // }else{
        //     $tt = $ksRndMap->getNodeX($path_value);
        //     if($lastArr['x']==$tt){
        //         $lastArr['x_count'] = $lastArr['x_count']+1;
        //         $lastArr['y_count'] = 0; 
        //         $flag = true;
        //     }else{
        //         $lastArr['x'] = $tt;
        //         $lastArr['x_count'] = 0;  
        //     }
        // }
        // if(!$flag){
        //     if(!isset($lastArr['y'])) {
        //         $lastArr['y'] = $ksRndMap->getNodeY($path_value);
        //         $lastArr['y_count'] = 0;
        //     }else{
        //         $tt = $ksRndMap->getNodeY($path_value);
        //         if($lastArr['y']==$tt){
        //             $lastArr['y_count'] = $lastArr['y_count']+1;
        //             $lastArr['x_count'] = 0; 
        //         }else{
        //             $lastArr['y'] = $tt;
        //             $lastArr['y_count'] = 0;  
        //         }
        //     }
        // }
    // }

    // $last=array();
    // foreach ($lastArr as $key => $value) {
    //     if()
    // }
    return $tmpPathNew;
}



function get_search_result_json($table_name,$id,$where,$limit,$offset,$fields_str){
    global $debugMode, $time_log;
/*
{
    "data" : 128,
    "rows" : [{
            "realm" : "",
            "username" : "8614548144271",
            ...
            "acctStopDelay" : 0
        }, {
            ...
        }
    ],
    "success" : true
}
*/
    
    $data= array('data'=>0,'success'=>false,'rows'=>array());

    $tmp_sql = hp_mysql_count_sql($table_name,$where);

    $tmp_arr=get_data($tmp_sql);
    if($tmp_arr===false){
        if($debugMode) echo 'DEBUG: ' . __FUNCTION__ . '() MySQL Error ! ' . $tmp_sql . PHP_EOL;
        return $data;
    }
    if(isset($tmp_arr[0]['num'])){
        $tmp = intval($tmp_arr[0]['num']);
        if($tmp>0){
            $data['data'] = $tmp;
        }
    }

    $tmp_sql = high_performance_mysql_limit_sql($table_name,$id,$where,$limit,$offset,$fields_str);

    $ret =get_data($tmp_sql);
    if($ret===false){
        if($debugMode) echo 'DEBUG: ' . __FUNCTION__ . '() MySQL Error ! ' . $tmp_sql . PHP_EOL;
        return $data;
    }
    $data['success']=true;
    foreach ($ret as $key => $value) {
      unset($value['id']);
      $data['rows'][$key]=$value;
    }
    return $data;
}



function debug_map_part($x1,$y1,$w1,$h1,$output=1,$ccid=false){
    global $ksRndMap, $aStar, $w ,$h;
    global $debugMode, $time_log , $grids, $map_html_debug;

    echo 'DEBUG: ' . __FUNCTION__ . '(x1='.$x1.',y1='.$y1.',w1='.$w1.',h1='.$h1.')<br/>'.PHP_EOL;   
    $cc = get_color($ccid);

    echo 'DEBUG: ' . __FUNCTION__ . '() w='.$w.',h='.$h.',output='.$output.',ccid='.$ccid.'<br/>'.PHP_EOL;

    $ret_html = '';

    // $ret_html .= debug_map_html($grids);

    for ($iy=0; $iy < $h1 ; $iy++) { 
      for ($ix=0; $ix <$w1 ; $ix++) { 
          
        $pos = ($y1+$iy) * $w + $x1+$ix;
        // echo 'ix='.$ix.',iy='.$iy.',pos='.$pos.'<br/>'.PHP_EOL;
        // if(isset($grids[$pos])){
            $grids[$pos] = $pos.'#'.$cc;

        // }else{
          // echo 'miss ' . $pos;
          // while ( $pos<= count($grids)) {
          //   $grids[]=0;
          // }
          // $grids[$pos] = $pos;
        // }
      }
    }

    if($output){
      $ret_html .= debug_map_html($grids);
      $ret_html .='<hr color="red"/><br/><br/><br/>'.PHP_EOL.PHP_EOL.PHP_EOL;  
    }
    $map_html_debug = $ret_html;
    return $ret_html;
}


$debug_map_html_id = 0;

function debug_map_html(&$grids){
    global $w, $h ,$debugMode , $debug_map_html_id;

    $cell_height = '30px';
    $cell_width = '30px';

    $debug_map_html_id++;
    $map_html = '<h3>DEBUG MAP TABLE #'.$debug_map_html_id.'</h3>';

    $map_html .='<table align="center" border="1" cellspacing="0" cellpadding="0" class="printtab"><tbody>'.PHP_EOL;
    
    $map_html .= '<tr height="'.$cell_height.'">'.PHP_EOL;
    $map_html .= '<td width="'.$cell_width.'" id="xytd">&nbsp;</td>'.PHP_EOL;
    for ($i=0; $i < $w; $i++) { 
      $map_html .= '<td width="'.$cell_width.'" id="xtd_'.$i.'">x:'.$i.'</td>'.PHP_EOL;
    }
    $map_html .= '</tr>'.PHP_EOL;

    for($y = 0; $y < $h; $y++ ){
        $map_html .= '<tr height="'.$cell_height.'">'.PHP_EOL;
        
        $map_html .= '<td width="'.$cell_width.'" id="ytd_'.$y.'">y:'.$y.'</td>'.PHP_EOL;

        for($x=0; $x < $w; $x++ ){
          $c='';
          $style='';
            if(isset($grids[$y * $w + $x])){
              $vv = $grids[$y * $w + $x];
              $arr = explode('#', $vv);
              $v =$arr[0]; 
              if(count($arr)>1){
                $c =$arr[1]; 
                $style=' style="background-color:#'.$c.'" ';  
              }              
            }else{
              $v = 'miss';              
            }
            $map_html .= '<td width="32px" id="td_'.$x.'_'.$y.'" '.$style.' >'.$v.'</td>'.PHP_EOL;
        }
        $map_html .= '</tr>'.PHP_EOL;
    }
    return $map_html.'</tbody></table>'.PHP_EOL;
}

function debug_init_map($w, $h){
  $tmp_grids = array();
  for ($y = 0; $y < $h; $y ++) {
    for ($x = 0; $x < $w; $x ++) {
      // array_push($tmp_grids, 0);
      // $v = $y * $w + $x;
      // array_push($tmp_grids, $v);
      array_push($tmp_grids, '&nbsp;');
    }
  }
  return $tmp_grids;
}


$all_func_name_arr = array();

function get_func_debug_mode($funcName){
  global $all_func_name_arr ,$debugMode;
  if(!$debugMode) return false;
  $func_name = strtolower(trim($funcName));
  // echo 'DEBUG: ' . __FUNCTION__ . '('.$func_name.')'. PHP_EOL;   
  if(!in_array($func_name, $all_func_name_arr)){
    array_push($all_func_name_arr, $func_name);
  }

  switch ($func_name) {
    case 'ksleaf::ksleaf':
      $ret = false;
      break;

    case 'ksleaf::set_color_config':
      $ret = false;
      break;
    
    case 'ksleaf::split':
      $ret = false;
      break;

    case 'ksleaf::_fill_map_with_rect': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::fillmaps': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::_bsp_rand_xy': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::createhall': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::createrooms': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksbsp::bsp': 
      $ret = false;
      break;

    case 'get_color': 
      $ret = false;
      break;

    case 'convert_map_grids';
      $ret = false;
      break;

    default:
      $ret = true;
      break;
  }
  return $ret;
}


function map_color($id){
  switch ($id) {
    case 'leaf':
      return 1; //#dddddd
      break;

    case 'room':
      return 4; //#666666
      break;
    
    case 'hall':
      return 33; //#cc6600
      break;

    default:
      return false;   //随机颜色
      break;
  }

}

function get_top_color($pathSetId,$v,$k){
  //v=0;788#4;788#cc6600;788#1
  $max_cc = get_top_cell_color($v);
  if(strlen($max_cc)==6) return $cc;
  if($max_cc>0) 
    return get_color($max_cc);
  return get_color($pathSetId);
}

function get_top_cell_color($v){
  // global $color_config;
  // if($color_config){
  //   $tmpArr = explode(';', $color_config['sort']);
  //   $sortArr=array();
  //   foreach ($tmpArr as $key => $value) {
  //     if(isset($color_config[$value])){
  //       $sortArr[$value]=$key;
  //     }
  //   }
  // }
  //v=0;788#4;788#cc6600;788#1
  $mode=2;  
  if($mode==1){
    $max_cc = -1;
    $max_top = 999;    
  }else{
    $max_cc = 999;
    $max_top = -1;
  }

  if($v==='0') return $max_cc;

  $arr = explode(';', $v);  
  foreach ($arr as $key => $value) {
    if(stripos($value, '#')!==false){
      $arr2 = explode('#', $value);
      $cc = $arr2[count($arr2)-1];
      if(strlen($cc)==6) $cc = $max_top;
      if($mode==1){
        if($cc > $max_cc) $max_cc = $cc;
      }else{
        if($cc < $max_cc) $max_cc = $cc;
      }
    }
  }
  return $max_cc;  
}


 //检查该地图做标是否可以探索
function check_map_pos_can_exp($uid,$x,$y){
	$ret_data=array('err_code'=>0,'func_name'=>__FUNCTION__,'msg'=>'');	

	if($x==1000 && $y==1000){
		$ret_data['msg']='camp';
		$ret_data['err_code']=1;
		return $ret_data;
	}

//SELECT `id`, `title`, `code`, `is_his`, `category`, `thumbnail_id`, `block_id`, `path_id`, `door_id`, `bg_img`, `pos_x`, `pos_y`, `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9`, `create_date`, `modify_date`, `parent_id`, `sort` FROM `shdic_sc2015_map_info` WHERE 1

	$table = real_table_name('map_info');
	$tmp_sql=prepare("SELECT * FROM `".$table."` WHERE `is_his`=0 AND `pos_x` = ?s AND `pos_y` = ?s ",
		array($x,$y));
	if( $map_data = get_line( $tmp_sql ) ){
		
//SELECT `id`, `title`, `info_desc`, `code`, `is_his`, `category`, `thumbnail_id`, `path_pos`, `enter_item_id`, `loot_set_id`, `door_num`, `door_pos`, `has_child`, `bg_img`, `ca_x`, `ca_y`, `ca_z`, `create_date`, `modify_date`, `parent_id`, `sort` FROM `shdic_sc2015_map_block_info` WHERE 1
		$block_id = intval($map_data['block_id']);
		if($block_id>0){
			$table = real_table_name('map_block_info');
			$tmp_sql=prepare("SELECT * FROM `".$table."` WHERE `id`= ?i ",array($block_id));

			$ret_data['map']=array();
			foreach ($map_data as $key => $value) {
				$ret_data['map'][$key]=$value;
			}

			if( $mb_data = get_line( $tmp_sql ) ){

				if(isset($mb_data['door_num']) && intval($mb_data['door_num'])>0){
					//有入口

					$ret_data['map_block']=array();
					foreach ($mb_data as $key => $value) {
						$ret_data['map_block'][$key]=$value;
					}

					if(isset($mb_data['enter_item_id']) && intval($mb_data['enter_item_id'])>0){
						//检查玩家是否携带了制定物品
						//TODO
			
					}
		
				}else{
					$ret_data['msg']='找不到可以进入的入口！';
					$ret_data['err_code']=5;
					return $ret_data;
				}
			}else{
				$ret_data['msg']='miss map_block_info! #2';
				$ret_data['err_code']=4;
				return $ret_data;
			}

		}else{
			$ret_data['msg']='miss map_block_info!';
			$ret_data['err_code']=3;
			return $ret_data;
		}
	}else{
		$ret_data['msg']='miss map_info!';
		$ret_data['err_code']=2;
		return $ret_data;
	}
	return $ret_data;
}

function get_item_name($itm_id){
  //FIXME 20150422
  // return '物品名称#'.$itm_id;

//SELECT `id`, `ffuid`, `title`, `desc`, `is_his`, `category`, `sub_category`, `max_holding`, `max_stack`, `single_weight`, `quality`, `in_use`, `num1`, `num2`, `durable`, `create_date`, `modify_date` FROM `shdic_sc2015_item_info` WHERE 1
  $table = real_table_name('item_info');
  $tmp_sql=prepare("SELECT * FROM `".$table."` WHERE `is_his`=0 AND `id` = ?s ", array($itm_id));
  if( $ret_data = get_line( $tmp_sql ) ){
    if(isset($ret_data['title']) && !empty($ret_data['title'])){
      return $ret_data['title'];
    }
  }

  return '物品名称#'.$itm_id;  
}

?>
<?php

